<template>
  <el-dialog :title="dialogType === 'add' ? 'Add User' : 'Modify Account Information'" v-model="dialogVisible"
    width="700px" :close-on-click-modal="false" @closed="handleDialogClosed">
    <el-form ref="formRef" :model="form" :rules="rules" label-width="180px" label-position="right">
      <el-form-item label="User name:" prop="username">
        <el-input v-model="form.username" placeholder="Please enter" :maxlength="100" :show-word-limit="true" />
      </el-form-item>

      <!-- 角色选择：管理员禁用变灰（仍显示当前值），普通账号可选 -->
      <el-form-item label="Role:" prop="roleId">
        <template v-if="isEditingAdmin">
          <el-input :model-value="selectedRoleLabel" disabled />
        </template>
        <template v-else>
          <el-select v-model="form.roleId" placeholder="Please select role" style="width: 100%" :loading="loadingRoles">
            <el-option v-for="role in availableRoles" :key="role.id" :label="role.displayName" :value="String(role.id)" />
          </el-select>
        </template>
      </el-form-item>

      <el-form-item label="User E-mail:" prop="email">
        <el-input v-model="form.email" placeholder="Please enter email" :maxlength="100" :show-word-limit="true"
          :disabled="dialogType === 'edit'" />
      </el-form-item>

      <el-form-item label="User phone number:" prop="mobile">
        <el-input v-model="form.mobile" placeholder="Please enter phone number" :maxlength="20" :show-word-limit="true"
          :disabled="dialogType === 'edit'" @input="handleMobileInput" />
      </el-form-item>

      <el-form-item label="Note:" prop="note">
        <el-input v-model="form.note" type="textarea" :rows="4" placeholder="Please enter note" :maxlength="200"
          :show-word-limit="true" />
      </el-form-item>
    </el-form>

    <template #footer>
      <div class="flex justify-end">
        <el-button @click="dialogVisible = false">Cancel</el-button>
        <el-button type="primary" @click="submitForm">Submit</el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script lang="ts" setup>
import { ref, reactive, watch, nextTick, computed, onMounted } from "vue";
import type { FormInstance, FormRules } from "element-plus";
import { roleApi } from "@/api/authority";
import { useAppStore } from "@/store";

const props = defineProps({
  visible: {
    type: Boolean,
    default: false
  },
  formData: {
    type: Object,
    default: () => ({})
  },
  dialogType: {
    type: String,
    default: "add" // 'add' 或 'edit'
  }
});

const emit = defineEmits(["update:visible", "submit-success"]);

// 获取当前用户信息
const store = useAppStore();
const currentUser = store.state.user;

// 表单引用
const formRef = ref<FormInstance>();
const dialogVisible = ref(props.visible);

// 角色列表
const roleList = ref<any[]>([]);
const loadingRoles = ref(false);

// 表单数据
const form = reactive({
  id: "",
  username: "",
  email: "",
  mobile: "",
  roleId: undefined as string | undefined,
  note: ""
});

// 角色映射
const roleMap = {
  1: 'Administrator',
  2: 'Operator',
  3: 'Installer',
  4: 'User'
};

// 判断是否为管理员账号
const isAdminAccount = computed(() => {
  return form.roleId === '1'; // Administrator
});

// 被编辑对象是否为管理员（基于原始表单数据判断）
const isEditingAdmin = computed(() => {
  const raw = (props.formData as any)?.roleId ?? (Array.isArray((props.formData as any)?.roleIdList) ? (props.formData as any)?.roleIdList[0] : undefined);
  return Number(((props.formData as any)?.isAdmin) ?? 0) === 1 || String(raw) === '1';
});

// 获取角色名称（当前实现不再使用，只保留管理员判断逻辑）

// 角色列表：仅在“编辑对象不是管理员”时排除管理员；其余不过滤
const availableRoles = computed(() => {
  return roleList.value
    .map(role => ({
      ...role,
      displayName: role.name || role.roleName || String(role.id)
    }));
});

// 选中角色的名称（用于管理员只读显示）
const selectedRoleLabel = computed(() => {
  const fromList = roleList.value.find((r: any) => String(r.id) === String(form.roleId));
  return (
    fromList?.name ||
    fromList?.roleName ||
    (props.formData as any)?.role ||
    (props.formData as any)?.roleName ||
    (String(form.roleId) === '1' ? 'Administrator' : String(form.roleId || ''))
  );
});

// 加载角色列表
const loadRoleList = async () => {
  loadingRoles.value = true;
  try {
    const response = await roleApi.getList();
    if (response.code === 0) {
      roleList.value = response.data || [];
    }
  } catch (error) {
    console.error('加载角色列表失败:', error);
  } finally {
    loadingRoles.value = false;
  }
};

// 组件挂载时加载角色列表
onMounted(() => {
  loadRoleList();
});

// 动态验证规则
const rules = computed<FormRules>(() => {
  const baseRules: FormRules = {
    username: [
      {
        required: true,
        message: "Please enter user name",
        trigger: "blur"
      },
      {
        max: 100,
        message: "User name cannot exceed 100 characters",
        trigger: "blur"
      }
    ],
    email: [
      {
        required: true,
        message: "Please enter email",
        trigger: "blur"
      },
      {
        type: "email",
        message: "Please enter valid email format",
        trigger: "blur"
      },
      {
        max: 100,
        message: "Email cannot exceed 100 characters",
        trigger: "blur"
      }
    ],
    mobile: [
      {
        required: true,
        message: "Please enter phone number",
        trigger: "blur"
      },
      {
        pattern: /^\d+$/,
        message: "电话号码只能输入数字",
        trigger: "blur"
      },
      {
        max: 20,
        message: "Phone number cannot exceed 20 characters",
        trigger: "blur"
      }
    ],
    note: [
      {
        max: 200,
        message: "Note cannot exceed 200 characters",
        trigger: "blur"
      }
    ]
  };

  // 角色始终必填：管理员禁用但回填原值，保持红星与校验
  baseRules.roleId = [
    {
      required: true,
      message: "Please select role",
      trigger: "change"
    }
  ];

  return baseRules;
});

// 重置表单
const resetForm = () => {
  form.id = "";
  form.username = "";
  form.email = "";
  form.mobile = "";
  form.roleId = undefined;
  form.note = "";
};

// 监听visible属性变化
watch(
  () => props.visible,
  val => {
    dialogVisible.value = val;
  }
);

// 监听dialogVisible变化，同步到父组件
watch(
  () => dialogVisible.value,
  val => {
    emit("update:visible", val);
  }
);

// 监听传入的表单数据
watch(
  () => props.formData,
  val => {
    if (Object.keys(val).length > 0) {
      // 重置表单
      resetForm();

      // 设置表单数据
      form.id = val.id || "";
      form.username = val.username || "";
      form.email = val.email || "";
      form.mobile = val.mobile || "";
      // 兼容后端不同字段：roleId 或 roleIdList（取第一个），统一为字符串，避免长整型精度问题
      const rawRoleId = (val as any).roleId ?? (Array.isArray((val as any).roleIdList) ? (val as any).roleIdList[0] : undefined);
      form.roleId = rawRoleId != null && rawRoleId !== '' ? String(rawRoleId) : undefined;
      form.note = val.note || "";
    }
  },
  { immediate: true, deep: true }
);

// 提交表单
const submitForm = async () => {
  if (!formRef.value) return;

  await formRef.value.validate((valid, fields) => {
    if (valid) {
      // 统一计算最终 roleId：优先表单值；否则回退原值（兼容 roleIdList）；始终为字符串
      const finalRoleIdRaw =
        form.roleId ??
        (props.formData as any)?.roleId ??
        (Array.isArray((props.formData as any)?.roleIdList)
          ? (props.formData as any)?.roleIdList[0]
          : undefined);
      const finalRoleId = finalRoleIdRaw != null && finalRoleIdRaw !== '' ? String(finalRoleIdRaw) : undefined;

      // 构建提交数据：始终带 roleId，管理员只是 UI 禁用
      const submitData: any = {
        id: form.id,
        username: form.username,
        email: form.email,
        mobile: form.mobile,
        note: form.note,
        ...(finalRoleId ? { roleId: finalRoleId } : {}),
        isAdd: props.dialogType === "add"
      };

      emit("submit-success", submitData);
    }
  });
};

// 处理电话号码输入，只允许数字
const handleMobileInput = (value: string) => {
  // 过滤非数字字符
  const numericValue = value.replace(/\D/g, '');
  form.mobile = numericValue;
};

// 处理对话框关闭
const handleDialogClosed = () => {
  resetForm();
};
</script>
